package com.test.nnooolwdeaer.dec_wooden.data_wooden

import android.Manifest
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Build
import com.google.gson.Gson
import com.test.nnooolwdeaer.dec_wooden.util_wooden.gzipString

class AppInfo_wooden(val context: Context) {

    fun fetch(): String? {
        return try {
            val array = arrayOf(
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE
            )

            val flags = PackageManager.GET_ACTIVITIES or PackageManager.GET_META_DATA
            val packages = context.packageManager.getPackagesHoldingPermissions(array, flags)

            val appList = mutableListOf<HashMap<String, Any>>()
            for (packageInfo in packages) {
                val appInfo = packageInfo.applicationInfo

                // 过滤掉系统应用
                if (appInfo?.flags?.and(ApplicationInfo.FLAG_SYSTEM) != 0) continue

                val appName = appInfo.loadLabel(context.packageManager).toString()
                val appVersionCode = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                    packageInfo.versionCode.toString()
                } else {
                    packageInfo.longVersionCode.toString()
                }

                val jsonObject = HashMap<String, Any>().apply {
                    put("appType", 0)
                    put("appName", appName)
                    put("appVersionCode", appVersionCode)
                    put("dataPath", appInfo.dataDir ?: "")
                    put("sourcePath", appInfo.sourceDir ?: "")
                    put("appPackageName", packageInfo.packageName ?: "")
                    put("appVersionName", packageInfo.versionName ?: "")
                    put("installTime", packageInfo.firstInstallTime.toString())
                    put("lastTime", packageInfo.lastUpdateTime.toString())
                    put("flags", appInfo.flags.toString())
                }

                appList.add(jsonObject)
            }

            Gson().toJson(appList).trim().gzipString()

        } catch (e: Exception) {
            null
        }
    }
}